<template>
  <div class="app-container">
     <el-row :gutter="20">
       <el-col :span="4" :xs="24" class="cate">
              <!-- <treeselect class="treeselect" placeholder="请选择" v-model="queryParams.classifyId" :multiple="false" :options="options" :show-count="true"/> -->
      
      <el-tree :data="options" :props="defaultProps" @node-click="handleNodeClick"></el-tree>            
        
        
        </el-col>  
      <el-col :span="20" :xs="24">
        <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">


          <el-form-item label="食物编码" prop="code">
            <el-input
              v-model="queryParams.code"
              placeholder="请输入食物编码"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
          <el-form-item label="食物名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入食物名称"
              clearable
              @keyup.enter.native="handleQuery"
            />
          </el-form-item>
      
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
          <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['food:sample:add']"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['food:sample:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['food:sample:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['food:sample:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="sampleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="食物名称" align="center" prop="name" />
      <el-table-column label="食物编码" align="center" prop="code" />

      <el-table-column label="图片" align="center">
        <template slot-scope="scope">
          <div class="top-img">
          <img :src="'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/'+scope.row.cover[0].url" v-if="scope.row.cover[0]" class="avatar"/> 
          </div>
        </template>
      </el-table-column>  

      <el-table-column label="食品分类" width="100" align="center" prop="classifyName" />
      <!-- <el-table-column label="食品图片" align="center" prop="cover" /> -->

      <!-- <el-table-column label="描述" align="center" prop="describe" /> -->
      <!-- <el-table-column label="采样日期" align="center" prop="sampleDt" /> -->
      <!-- <el-table-column label="采样地点" align="center" prop="sampleAddress" /> -->
      <!-- <el-table-column label="产地" align="center" prop="producer" /> -->
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
        <el-col :span="1.5">
          <el-button
            type="success"
            plain
            icon="el-icon-edit"
            size="mini"
            @click="handleToDetail(scope.row)"
            v-hasPermi="['food:sample:edit']"
          >元素管理</el-button>
        </el-col>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['food:sample:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['food:sample:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />  
      </el-col>


  </el-row>




    <!-- 添加或修改《中国食物成分》食物样品描述对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="食物名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>       
        <el-form-item label="食物类别" prop="classifyId">
          <treeselect class="treeselect" placeholder="请选择" :disable-branch-nodes="true" v-model="form.classifyId" :multiple="false" :options="options" :show-count="true"/>
        </el-form-item>
        <el-form-item label="食物编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入食物编码" />
        </el-form-item>
        <el-form-item label="食品图片" prop="cover">
            <el-upload
              ref="upload"
              list-type="picture-card"
              :on-remove="handleRemove"
              :http-request="handleUploadFile"
              :file-list="fullCover"
              action="https://jsonplaceholder.typicode.com/posts/"
              >
              <i class="el-icon-plus"></i>
            </el-upload>
        </el-form-item>        

        <el-form-item label="英文名称">
          <el-input v-model="form.enName" placeholder="请输入英文名称" />
        </el-form-item>
        <!-- <el-form-item label="食物描述" prop="describe">
          <el-input v-model="form.describe" type="textarea" placeholder="请输入内容" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listSample, getSample, delSample, addSample, updateSample } from "@/api/food/foodmanage";
import { listFoodclassify } from "@/api/food/foodclassify";
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import {
	put,
	getUrl,
} from '@/components/Upload/uploadOss.js'

export default {
  name: "Sample",
  components: { Treeselect }, 
  watch:{
    'form.cover'() {
      if(this.form.cover){
        this.fullCover = this.form.cover.map(item => (
                {
                  ...item,
                  url: 'http://health-fcd.oss-cn-hangzhou.aliyuncs.com/' + item.url
                }
          )
        )
      }
      console.log('233',this.fullCover);
    }
  }, 
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,   
      fullCover: [],
      
      defaultProps: {
        children: 'children',
        label: 'label'
      },    


      options: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 《中国食物成分》食物样品描述表格数据
      sampleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        classifyId: null,
        code: null,
        name: null,
        enName: null,
        describe: null,
        sampleDt: null,
        sampleAddress: null,
        producer: null,
        orderNum: null,
        status: null
      },
      // 表单参数
      form: {
        cover: []
      },
      // 表单校验
      rules: {
        classifyId: [
          { required: true, message: "食物类别不能为空", trigger: "blur" }
        ],
        code: [
          { required: true, message: "食物编码不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        enName: [
          { required: true, message: "英文名称不能为空", trigger: "blur" }
        ],
        describe: [
          { required: true, message: "食物描述不能为空", trigger: "blur" }
        ],
        sampleDt: [
          { required: true, message: "采样日期不能为空", trigger: "blur" }
        ],
        sampleAddress: [
          { required: true, message: "采样地点不能为空", trigger: "blur" }
        ],
        producer: [
          { required: true, message: "产地不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getOptionList();
  },
  methods: {
		handleUploadFile(option) {
				this.loading = true
				//获取上传后的url
				const _name = this.getDate() + '/' + option.file.uid + '.' + option.file.name.split('.')[1]
				put(_name, option.file).then((res) => {
					if (res) {
						getUrl(res.name).then((rel) => {
							this.form.cover.push({
                url: _name
              })
						})
            console.log('static',this.form.cover);
					} else {
					}
            this.loading = false
				})
		},

		// 获取当前年月日
		getDate() {
			const date = new Date()
			var year = date.getFullYear()
			var month = date.getMonth() + 1
			var day = date.getDate()
			month = month > 9 ? month : '0' + month
			day = day < 10 ? '0' + day : day
			var today = year + month + day
			return today
		},
    handleRemove(file, fileList) {
      console.log(file);
      this.form.cover = this.form.cover.filter((item)=>('http://health-fcd.oss-cn-hangzhou.aliyuncs.com/'+item.url) != file.url)
      console.log(this.form.cover);
    },
      handlePictureCardPreview(file) {
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },    

    handleNodeClick(data){
      console.log('static',data.$treeNodeId);
      if(!data.children){
        this.queryParams.classifyId = data.id;
        this.getList();
      }
    },
  
      getOptionList(){
        listFoodclassify({
            page: 1,
            pageSize: 200,
        }).then(response => {
            this.options = this.toTree(response.rows);
        });
      },    
    	toTree(treeData){
        console.log('111222',treeData);
        let tableData = [];
        for (var i = 0; i < treeData.length; i++) {
          if (treeData[i].parentId == 0) {
            // console.log(treeData[i].name);
            let obj = {}
            let children = []
            obj.label = treeData[i].name
            obj.id = treeData[i].id
            obj.versionId = treeData[i].versionId
            for (var j = 0; j < treeData.length; j++) {
              let childer = []
              if (treeData[j].parentId !== 0 && treeData[j].parentId == treeData[i].id) {
                let list = {}
                list.label = treeData[j].name
                list.id = treeData[j].id
                list.versionId = treeData[j].versionId
                children.push(list)
              }
            }
            obj.children = children
            tableData.push(obj)
          }
        }
            return  tableData;  
     }, 
    /** 查询《中国食物成分》食物样品描述列表 */
    getList() {
      this.loading = true;
      listSample(this.queryParams).then(response => {
        this.sampleList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        classifyId: null,
        code: null,
        name: null,
        enName: null,
        describe: null,
        sampleDt: null,
        sampleAddress: null,
        producer: null,
        remark: null,
        orderNum: null,
        updateTime: null,
        updateBy: null,
        createTime: null,
        createBy: null,
        delFlag: null,
        status: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.cover = [];
      this.form.classifyId =this.queryParams.classifyId;
      this.open = true;
      this.title = "添加《中国食物成分》食物样品描述";

    },
    handleToDetail(row) {
       this.$router.push('/food/detail?id='+ row.id)
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getSample(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改《中国食物成分》食物样品描述";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateSample(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addSample(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除《中国食物成分》食物名称为"' + row.name + '"的数据项？').then(function() {
        return delSample(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('food/sample/export', {
        ...this.queryParams
      }, `sample_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>


<style lang="scss" scoped>
.cate{
  margin-top: 50px;
}
.top-img{
  width: 100%;
  text-align: center;
  display: flex;
  justify-content: center;
}

  .avatar {
    width: 58px;
    height: 58px;
    display: block;
  }

</style>
